package com.ketai.dao;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @Author:长沙科泰梦想学院
 * @Description:
 * @Date:Create In 2022/6/16 11:25
 **/
public class BaseDao {

    private Connection conn;
    private PreparedStatement pstm;


    public void getConnection () throws NamingException, SQLException {

        if (conn == null || conn.isClosed()) {
            Context context = new InitialContext();
            DataSource dataSource = (DataSource) context.lookup("java:comp/env/jdbc/microblog");
            conn = dataSource.getConnection();
        }

    }

    public ResultSet query (String sql, Object[] params) throws SQLException, NamingException {
        // 获取连接对象
        getConnection();

        pstm = conn.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }
        }

        return pstm.executeQuery();

    }


    public int curdMethod (String sql, Object[] params) throws SQLException, NamingException {
        getConnection();
        pstm = conn.prepareStatement(sql);
        if (params != null) {
            for (int i = 0; i < params.length; i++) {
                pstm.setObject(i + 1, params[i]);
            }

        }

       int  rs= pstm.executeUpdate();
        closeAll(null);

        return rs;


    }

    public void closeAll (ResultSet rs) {
        try {
            if (rs != null) {
                rs.close();
            }
            if (pstm != null) {
                pstm.close();
            }
            if (conn != null) {
                conn.close();
            }

        } catch (SQLException e) {

        }

    }

}
